﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using ThingyCloudWPF.Network;
using ThingyCloudWPF.World;

namespace ThingyCloudWPF
{
	public class Program
	{
		private MessageServer mserver;
		private ParleVisionReader reader;
		private Thread readerThread;

		//static void Main(string[] args)
		public Program(MainWindow mw)
		{
			Debug.Clear();

			// Startup debug stuffies
			Debug.WriteLine(Globals.Separator);
			Debug.WriteLine("ThingyCloud v1.0");
			Debug.WriteLine(Globals.Separator);
			Debug.WriteLine("Booting up... Should be done real quick!");

            // Start up our message server
            Debug.WriteLine("Starting up message server...");
            mserver = MessageServer.Instance;

			// Create the network reader
			Debug.WriteLine("Creating ParleVision network reader...");
			reader = new ParleVisionReader("127.0.0.1", 1337);
			readerThread = new Thread(new ThreadStart(reader.Listen));
			readerThread.Start();

			// Now it's time to create the scene
			Debug.WriteLine("Creating world scene...");
			Scene scene = new Scene();
			Thread sceneThread = new Thread(new ThreadStart(scene.Live));
			sceneThread.Start();

			// Attach event handlers
			reader.BlobChanged += new EventHandler<Events.BlobChangedEventArgs>(scene.BlobChanged);

			mserver.MessageQueued += new EventHandler<Events.MessageQueuedArgs>(mw.MessageQueued);

			/*
			// hit 'q' to abort operations
			while (Console.ReadKey().Key != ConsoleKey.Q);

			Debug.WriteLine(Globals.Separator);
			Debug.WriteLine(Globals.Separator);
			Debug.WriteLine("Received interrupt! Quitting...");
			// When we're here it means we need to quit!

			// Stop message server
			mserver.Stop();

			// Stop the parlevision reader and wait for the thread
			Debug.WriteLine("Stopping ParleVision reader...");
			reader.Stop();
			readerThread.Join();

			// Stop the scene and wait for thread
			Debug.WriteLine("Stopping scene...");
			scene.Extinct();
			sceneThread.Join();

			Debug.WriteLine("That's it! Hit any key to abort. Goodbye!");
			Console.ReadKey();
			*/
		}
	}
}
